<template>
  <div class="order">
    <nav-bar
      title="提交订单"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <submit-bar
      :price="sumPrice"
      button-text="提交订单"
      is-link
      :disabled="!sumPrice"
      @click="show = true"
    ></submit-bar>
    <action-sheet
      v-model:show="show"
      :actions="actions"
      cancel-text="取消"
      description="本服务由支付宝（中国）网络技术有限公司提供"
      :closeable="true"
      :close-on-click-action="false"
      @select="buy"
    />
    <card
      v-for="item in carts"
      :num="item.amount"
      :price="item.product.price"
      :title="item.product.name"
      :thumb="dalImg(item.product.coverImage)"
    />
  </div>
</template>
<script setup>
import { ActionSheet, SubmitBar, NavBar, Card, Toast } from "vant";
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { loadCartAPI } from "../server/shop-carts";
import { loadProductByIdAPI } from "../server/products";
import { sendOrderAPI } from "../server/order";
import { userInfoAPI } from "../server/auth";
import { dalImg } from "../utils/tools";

const { query } = useRoute();
const sumPrice = ref(0);
// console.log(query.id);
const show = ref(false);
const actions = [
  { subname: "支付宝账号", name: "188******35" },
  { subname: "中国银行立减", name: "-￥2.00" },
  { name: "中国银行储蓄卡（2276）" },
  { name: "立即支付", color: "#ee0a24" },
];
const router = useRouter();
const carts = ref([]);
// 购物车返回上一页
const onClickLeft = () => {
  // history.back();
  router.go(-1);
};
const loadDataFromServer = () => {
  //   判断是从详情页还是购物车跳进来的
  if (query.id) {
    loadProductByIdAPI(query.id).then((res) => {
      //   console.log(res.data);
      carts.value.push({ amount: 1, product: res.data });
      // 计算商品总价
      sumPrice.value = res.data.price * 100;
    });
  } else {
    loadCartAPI().then((res) => {
      //   console.log(res);
      //   console.log(res.data);
      carts.value = res.data
        .filter((item) => item.product)
        .map((item) => ({ ...item, checked: false }));
      // 计算商品总价
      sumPrice.value =
        carts.value.reduce(
          (pre, cur) => pre + cur.amount * cur.product.price,
          0
        ) * 100;
    });
  }
};
// 初始化先加载购物车数据
loadDataFromServer();

// 立即支付提交订单
const buy = (action = ActionSheetAction, index = 3) => {
  // console.log(carts.value);
  // 获取用户信息，拿到用户名
  userInfoAPI().then((res) => {
    // console.log(res.data.userName);
    let userName = res.data.userName;
    // 提交订单
    let products = [];
    for (const cart of carts.value) {
      products.push({ product: cart.product.id, amount: cart.amount });
    }
    console.log(products);
    sendOrderAPI({
      products: products,
      receiver: userName,
      address: "中国",
    }).then((res) => {
      console.log(res);
    });
  });
  Toast.success("支付成功");
  setTimeout(() => {
    router.push({
      name: "MyOrder",
    });
  }, 1000);
};
</script>
